package cn.edu.niit.server.web.rest;

import static cn.edu.niit.server.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import cn.edu.niit.server.IntegrationTest;
import cn.edu.niit.server.domain.UserFans;
import cn.edu.niit.server.repository.UserFansRepository;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link UserFansResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class UserFansResourceIT {

    private static final ZonedDateTime DEFAULT_FANS_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
    private static final ZonedDateTime UPDATED_FANS_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);

    private static final String ENTITY_API_URL = "/api/user-fans";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private UserFansRepository userFansRepository;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restUserFansMockMvc;

    private UserFans userFans;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static UserFans createEntity(EntityManager em) {
        UserFans userFans = new UserFans().fansTime(DEFAULT_FANS_TIME);
        return userFans;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static UserFans createUpdatedEntity(EntityManager em) {
        UserFans userFans = new UserFans().fansTime(UPDATED_FANS_TIME);
        return userFans;
    }

    @BeforeEach
    public void initTest() {
        userFans = createEntity(em);
    }

    @Test
    @Transactional
    void createUserFans() throws Exception {
        int databaseSizeBeforeCreate = userFansRepository.findAll().size();
        // Create the UserFans
        restUserFansMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userFans)))
            .andExpect(status().isCreated());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeCreate + 1);
        UserFans testUserFans = userFansList.get(userFansList.size() - 1);
        assertThat(testUserFans.getFansTime()).isEqualTo(DEFAULT_FANS_TIME);
    }

    @Test
    @Transactional
    void createUserFansWithExistingId() throws Exception {
        // Create the UserFans with an existing ID
        userFans.setId(1L);

        int databaseSizeBeforeCreate = userFansRepository.findAll().size();

        // An entity with an existing ID cannot be created, so this API call must fail
        restUserFansMockMvc
            .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userFans)))
            .andExpect(status().isBadRequest());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void getAllUserFans() throws Exception {
        // Initialize the database
        userFansRepository.saveAndFlush(userFans);

        // Get all the userFansList
        restUserFansMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(userFans.getId().intValue())))
            .andExpect(jsonPath("$.[*].fansTime").value(hasItem(sameInstant(DEFAULT_FANS_TIME))));
    }

    @Test
    @Transactional
    void getUserFans() throws Exception {
        // Initialize the database
        userFansRepository.saveAndFlush(userFans);

        // Get the userFans
        restUserFansMockMvc
            .perform(get(ENTITY_API_URL_ID, userFans.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(userFans.getId().intValue()))
            .andExpect(jsonPath("$.fansTime").value(sameInstant(DEFAULT_FANS_TIME)));
    }

    @Test
    @Transactional
    void getNonExistingUserFans() throws Exception {
        // Get the userFans
        restUserFansMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putNewUserFans() throws Exception {
        // Initialize the database
        userFansRepository.saveAndFlush(userFans);

        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();

        // Update the userFans
        UserFans updatedUserFans = userFansRepository.findById(userFans.getId()).get();
        // Disconnect from session so that the updates on updatedUserFans are not directly saved in db
        em.detach(updatedUserFans);
        updatedUserFans.fansTime(UPDATED_FANS_TIME);

        restUserFansMockMvc
            .perform(
                put(ENTITY_API_URL_ID, updatedUserFans.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(updatedUserFans))
            )
            .andExpect(status().isOk());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
        UserFans testUserFans = userFansList.get(userFansList.size() - 1);
        assertThat(testUserFans.getFansTime()).isEqualTo(UPDATED_FANS_TIME);
    }

    @Test
    @Transactional
    void putNonExistingUserFans() throws Exception {
        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();
        userFans.setId(count.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restUserFansMockMvc
            .perform(
                put(ENTITY_API_URL_ID, userFans.getId())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(userFans))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchUserFans() throws Exception {
        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();
        userFans.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserFansMockMvc
            .perform(
                put(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(TestUtil.convertObjectToJsonBytes(userFans))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamUserFans() throws Exception {
        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();
        userFans.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserFansMockMvc
            .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userFans)))
            .andExpect(status().isMethodNotAllowed());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateUserFansWithPatch() throws Exception {
        // Initialize the database
        userFansRepository.saveAndFlush(userFans);

        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();

        // Update the userFans using partial update
        UserFans partialUpdatedUserFans = new UserFans();
        partialUpdatedUserFans.setId(userFans.getId());

        restUserFansMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedUserFans.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedUserFans))
            )
            .andExpect(status().isOk());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
        UserFans testUserFans = userFansList.get(userFansList.size() - 1);
        assertThat(testUserFans.getFansTime()).isEqualTo(DEFAULT_FANS_TIME);
    }

    @Test
    @Transactional
    void fullUpdateUserFansWithPatch() throws Exception {
        // Initialize the database
        userFansRepository.saveAndFlush(userFans);

        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();

        // Update the userFans using partial update
        UserFans partialUpdatedUserFans = new UserFans();
        partialUpdatedUserFans.setId(userFans.getId());

        partialUpdatedUserFans.fansTime(UPDATED_FANS_TIME);

        restUserFansMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedUserFans.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(partialUpdatedUserFans))
            )
            .andExpect(status().isOk());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
        UserFans testUserFans = userFansList.get(userFansList.size() - 1);
        assertThat(testUserFans.getFansTime()).isEqualTo(UPDATED_FANS_TIME);
    }

    @Test
    @Transactional
    void patchNonExistingUserFans() throws Exception {
        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();
        userFans.setId(count.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restUserFansMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, userFans.getId())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(userFans))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchUserFans() throws Exception {
        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();
        userFans.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserFansMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, count.incrementAndGet())
                    .contentType("application/merge-patch+json")
                    .content(TestUtil.convertObjectToJsonBytes(userFans))
            )
            .andExpect(status().isBadRequest());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamUserFans() throws Exception {
        int databaseSizeBeforeUpdate = userFansRepository.findAll().size();
        userFans.setId(count.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restUserFansMockMvc
            .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(userFans)))
            .andExpect(status().isMethodNotAllowed());

        // Validate the UserFans in the database
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteUserFans() throws Exception {
        // Initialize the database
        userFansRepository.saveAndFlush(userFans);

        int databaseSizeBeforeDelete = userFansRepository.findAll().size();

        // Delete the userFans
        restUserFansMockMvc
            .perform(delete(ENTITY_API_URL_ID, userFans.getId()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<UserFans> userFansList = userFansRepository.findAll();
        assertThat(userFansList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
